﻿namespace _3DExercise
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    public static class PathStorage
    {
        //// Create a static class PathStorage with static methods to save and load paths from a text file.
        //// Use a file format of your choice.

        private static Path pathForStorageManipulations;
        private static List<Path> listOfPaths;

        static PathStorage()
        {
            AllSavedPaths = new List<Path>();
        }

        public static Path PathForFromStorage
        {
            get
            {
                return pathForStorageManipulations;
            }

            private set
            {
                pathForStorageManipulations = value;
            }
        }

        public static List<Path> AllSavedPaths
        {
            get
            {
                return listOfPaths;
            }

            private set
            {
                listOfPaths = value;
            }
        }

        public static void SavePaths(Path pathForAdd)
        {
            List<Path> tempy = AllSavedPaths;
            tempy.Add(pathForAdd);
            AllSavedPaths = tempy;

            using (StreamWriter output = new StreamWriter(@"../../Paths.txt"))
            {
                foreach (var path in listOfPaths)
                {
                    foreach (var point in path.PathByPoints)
                    {
                        output.WriteLine(point.CoordX + " " + point.CoordY + " " + point.CoordZ);
                    }

                    output.WriteLine(new string('-', 5));
                }
            }
        }

        public static List<Path> LoadPaths()
        {
            using (StreamReader readPaths = new StreamReader(@"../../Paths.txt"))
            {
                List<Point3D> tempyPoints = new List<Point3D>();
                List<Path> tempyPaths = new List<Path>();

                string line = readPaths.ReadLine();

                while (line != null)
                {
                    if (char.IsNumber(line[0]) == true || char.IsNumber(line[1]) == true || line[1] == '.')
                    {
                        string[] point = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        tempyPoints.Add(new Point3D(decimal.Parse(point[0]), decimal.Parse(point[1]), decimal.Parse(point[2])));
                    }
                    else if (line[1] == '-')
                    {
                        tempyPaths.Add(new Path(tempyPoints));
                        tempyPoints = new List<Point3D>();
                    }
                    
                    line = readPaths.ReadLine();
                }

                AllSavedPaths = tempyPaths;
            }

            return AllSavedPaths;
        }
    }
}